package com.tmq.diancan.controller;

import com.tmq.diancan.dto.DiancanOrderDetailDTO;
import com.tmq.diancan.enums.ResultEnum;
import com.tmq.diancan.exception.ServiceException;
import com.tmq.diancan.form.OrderForm;
import com.tmq.diancan.service.IDiancanOrderDetailService;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.api.ResultCode;
import org.springblade.core.tool.utils.Func;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单 控制器
 *
 * @author tangmqb
 * @since 2020-03-21
 */
@RestController
@RequestMapping("/buyer/order")
@Slf4j
public class BuyerOrderController {

    @Autowired
    private IDiancanOrderDetailService orderService;

//    @Autowired
//    private BuyerService buyerService;

    //创建订单
    @PostMapping("/create")
    public R<Map<String, String>> create(@Valid OrderForm orderForm,BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            log.error("【创建订单】参数不正确, orderForm={}", orderForm);
            throw new ServiceException(ResultEnum.PARAM_ERROR);
        }

        DiancanOrderDetailDTO orderDTO = Func.copy(orderForm,DiancanOrderDetailDTO.class);
        if (CollectionUtils.isEmpty(orderDTO.getOrderDetailList())) {
            log.error("【创建订单】购物车不能为空");
            throw new ServiceException(ResultEnum.CART_EMPTY);
        }

        DiancanOrderDetailDTO createResult = orderService.create(orderDTO);

        Map<String, String> map = new HashMap<>();
        map.put("orderId", createResult.getOrderId());
        return R.data(map);
    }

}
